<template>
    <view class="content">
        <view class="main">
            <scroll-view scroll-y="true" @scroll="handleScroll" style="height: 100vh;" :scroll-top="scrollTop"
                ref="myScrollView" show-scrollbar="false">
                <loading :loadingIsShow="loadingIsShow" v-if="!isrefresher"></loading>
                <view v-show="!loadingIsShow">
                    <!-- 这里是页面其他内容 -->
                    <view class="content-top fixed_top" :style="bgOpacity" id="content_top">
                        <van-nav-bar left-arrow @click-left="onClickLeft" class="fixed_top" id="navBar"> </van-nav-bar>
                        <view class="tabBox" :class="{ top_display: !scrolling }" id="tabBox" :style="scrollMT">
                            <view class="tabs white">
                                <view class="tabbar-item tab-item" v-for="(ite, index) in tabBarList"
                                    @click="changeTab(index, $event, ite.typeName)"
                                    :class="{ active: index === currentIndex, option: currentIndex === 0, }" :key="index">
                                    {{ ite.typeName }}
                                </view>
                            </view>
                        </view>
                    </view>
                    <view class="main-container" ref="container"
                        :class="{ 'element_to_animate': isAnimated,'animate_class': isAnimated, }">
                        <!-- 商品图片  五张轮播 -->
                        <view class="goodsImg" ref="goodsImg">
                            <swiper class="top_swiper" autoplay="false" :indicator-dots="false"
                                indicator-active-color="#FFFFFF" :indicator-width="20" ref="webpage"
                                :current="currentSwiper" @change="changeSwiper($event)">
                                <swiper-item v-for="(swiper_item, s) in sliderImageList" :id="s" :key="s">
                                    <img :src="swiper_item" alt="">
                                </swiper-item>
                            </swiper>
                            <!-- 数字五张 -->
                            <view class="swiper_item_num">{{ currentSwiperItem + 1 }} / {{ sliderImageList.length }}</view>
                            <!-- <template v-if="params.biaozhi !== 'find'">
                                <view class="status_tips" v-if="ebStoreProduct.stock === 0">已售罄</view> -->
                            <view class="status_tips" v-if="isRemove">已下架</view>
                            <!-- </template> -->
                            <!-- <template v-if="params.biaozhi === 'find'">
                                <view class="group_status_tips">
                                    <view class="status_tips_left">
                                        <view class="joinPeopleNum">{{joinPeopleNum}}人已拼团</view>
                                        <view class="stopTimeTips">距活动结束：</view>
                                    </view>
                                    <view class="status_tips_right" v-if="remainingTime==='未开始' || remainingTime==='已结束'">
                                        {{remainingTime}}</view>
                                    <view class="status_tips_right" v-else>
                                        <template v-if="days>0"><text>{{days}}</text> <span>天</span> </template>
                                        <template v-if="days>0"><text>{{hours}}</text> <span>时</span></template>
                                        <template v-if="hours>0"> <text>{{minutes}}</text> <span>分</span> </template>
                                        <template> <text>{{seconds}}</text> <span>秒</span> </template>
                                    </view>
                                </view>
                            </template> -->
                        </view>
                        <!-- 商品信息 -->
                        <view class="goods_content" id="goods_content">
                            <span class="goods_detail"> <span class="text"> {{ ebStoreProduct.storeName }} </span> </span>
                            <view class="goods_tips" v-if="tipsList.length>0">
                                <view class="tips_item" v-for="(item, index) in tipsList.slice(0,3)" :key="index">{{ item.name }} </view>
                            </view>
                            <view class="goods_price">
                                <view class="goods_price_num r13">¥{{ ebStoreProduct.price }}</view>
                                <view class="goods_price_text r8">最多可用</view>
                                <view class="goods_price_num"> <img
                                        src="https://17lelife-bucket.oss-cn-beijing.aliyuncs.com/WeChat-App-Picture/shangcheng/jinbi.png"
                                        alt="" style="height: 14px; width: 14px; margin-right: 7px;" /> {{
                                    ebStoreProduct.integral }}</view>
                            </view>
                        </view>
                        <!-- 口味 -->
                        <view class="goods-specs">
                            <view class="goods-specs-item" style="padding-bottom: 26px;" @tap="onClickSpecs">
                                <view
                                    style="display: flex;  height: 22px;line-height: 22px; align-items: center; font-size: 28rpx;">
                                    <template>
                                        <view class="goods-specs-selected">选择</view>
                                        <view class="goods-specs-item l20">共有{{ specsPriceList.length }}款可选</view>
                                    </template>
                                </view>
                                <view class="left-arrow" @tap="onClickSpecs"> <van-icon name="arrow" /> </view>
                            </view>
                            <view class="goods-specs-item" style="padding-bottom: 26px;" @tap="showNotes">
                                <view
                                    style="display: flex;  height: 22px;line-height: 22px; align-items: center; font-size: 28rpx;">
                                    <template>
                                        <view class="goods-specs-selected">须知</view>
                                        <view class="goods-specs-item l20">
                                            <!-- <span>{{formattedDates}}</span> -->
                                            <span v-if="productTimeConfig.minOrderHour&& productTimeConfig.minOrderHour>0">需提前{{productTimeConfig.minOrderHour}}分钟预约</span>
                                        </view>
                                    </template>
                                </view>
                                <view class="left-arrow" @tap="showNotes"> <van-icon name="arrow" /> </view>
                            </view>
                            <view class="goods-specs-item" style="padding-bottom: 26px;" @tap="showGuarantees" v-if="guarantees && guarantees.length>0">
                                <view
                                    style="display: flex;  height: 22px;line-height: 22px; align-items: center; font-size: 28rpx;">
                                    <template>
                                        <view class="goods-specs-selected">保障</view>
                                        <view class="goods-specs-item l20">{{ getGuaranteeText().join('  ·  ') }}</view>
                                    </template>
                                </view>
                                <view class="left-arrow" @tap="showGuarantees"> <van-icon name="arrow" /> </view>
                            </view>
                            <!-- <view class="goods-specs-item" style="padding-bottom: 26px;">
                                <view style="display: flex;  height: 22px;line-height: 22px; align-items: center; font-size: 28rpx;">
                                    <template>
                                        <view class="goods-specs-selected">参数</view>
                                        <view class="goods-specs-item l20">共有{{ specsPriceList.length }}款可选</view>
                                    </template>
                                </view>
                                <view class="left-arrow" @click="onClickSpecs"> <van-icon name="arrow" /> </view>
                            </view> -->

                        </view>
                        <!-- 优惠券 -->
                        <view class="coupon" v-if="couponsData.length>0">
                            <view class="coupon-item" style="display: flex;">
                                <view class="coupon-type" v-for="(item, index) in couponsData.slice(0,2)" :key="index">{{ item.name }}</view>
                            </view>
                            <view class="left-arrow" @click="onClickCoupons(index)">查看 <van-icon name="arrow"
                                    style="margin-left: 11px;" />
                            </view>
                        </view>
                        <!-- 用户评价 -->
                        <view class="user-judge" id="judge_box" :class="{ 'element_to_animate': isAnimatedJudge ,}">
                            <view class="user-judge-title">
                                <view class="title">用户评价</view>
                                <view class="left-arrow" @click="toJudgePage()">
                                    <text style="color: #b3b3b3; font-size: 26rpx;" v-if="productReplyNum<=100">{{productReplyNum }} 条评论</text>
                                    <text style="color: #b3b3b3; font-size: 26rpx;"  v-if="productReplyNum>100">100+条评论</text>
                                    <van-icon name="arrow" style="margin-left:8px;" />
                                </view>
                            </view>
                            <!-- 评价列表 -->
                            <view class="judge_content" v-if="productJudgeList.length>0">
                                <view class="userJudge_box">
                                    <!-- <view class="fixDiv"></view> -->
                                    <scroll-view class="top-menu-view userJudge_content" scroll-x="true"
                                        :class="(swiperCurrent + 1) === productJudgeList.length ? 'last-top-menu-view' : ''"
                                        :scroll-into-view="tabCurrent" :scroll-with-animation="true" show-scrollbar="false">
                                        <!-- 只展示有图片的评论 -->
                                        <view class="judgeContainer" v-for="(itemS, indexS) in productJudgeList.slice(0, 5)"  :id="'tabNum' + (indexS + 1)" :key="indexS"
                                            @click.stop="lookInfo(indexS, $event, itemS)">
                                            <view class="user_judge_top">
                                                <view class="user_img"> <img :src="itemS.mpComments.isAnonymous === 1 ? defaultAvatarUrl : (itemS.avatarUrl || defaultAvatarUrl)" alt=""> </view>
                                                <view class="user_info">
                                                    <view class="user_nicheng">  {{ itemS.mpComments.isAnonymous === 1 ? '匿名用户' : itemS.userNickName || '匿名用户' }} </view>
                                                    <view class="user_judge_date">{{itemS.mpComments.publishTime}} </view>
                                                </view>
                                            </view>
                                            <view class="judge_comment">{{ itemS.mpComments.content}}</view>
                                            <view class="judge_img" v-if="itemS.mpComments && itemS.mpComments.imageUrls && itemS.mpComments.commentImgUrls.length > 0 ">
                                                <view class="judge_img_item" v-for="(ele, val) in itemS.mpComments.commentImgUrls" :key="val">
                                                    <img :src="ele" alt="" mode="widthFix">
                                                </view>
                                            </view>
                                        </view>
                                    </scroll-view>
                                </view>
                            </view>
                        </view>
                        <!-- 商品详情 -->
                        <view class="goodsPic" id="goodsDetail" :class="{ 'element_to_animate': isAnimatedDetail }"
                            v-for="(item, index) in contentImage" :key="index">
                            <img :src="item" alt="" mode="widthFix">
                        </view>
                    </view>
                </view>
            </scroll-view>
        </view>
        <view class="goodsAction" v-if="!isRemove && !loadingIsShow">
            <van-goods-action id="goodact">
                <!-- <view class="shouqingTips" v-if="ebStoreProduct.stock === 0">
                    <view>商品补货中</view>
                    <view>到货提醒</view>
                </view> -->
                <van-goods-action-icon icon="service-o" size="20px" color="#ff6203" style="min-width: 35rpx !important;" />
                <van-goods-action-button color="#FF6203" text="立即购买" type="warning" @click="onClickBuy" />
            </van-goods-action>
        </view>
        <view class="goodsAction" v-else-if="isRemove && !loadingIsShow">
            <!-- <view class="shouqingTips" v-if="outOfStock"> <view>商品补货中</view> <view>到货提醒</view> </view>
            <view class="removeTips" v-if="isRemove">商品已下架，查看类似商品</view> -->
            <view class="goods_act_box">
                <van-goods-action id="goods_act" :safe-area-inset-bottom="false">
                    <!-- <view class="shouqingTips" v-if="outOfStock"> <view>商品补货中</view> <view>到货提醒</view> </view> -->
                    <view class="removeTips" v-if="isRemove">该服务商品已下架，查看类似商品</view>
                    <van-goods-action-icon icon="service-o" @click="onClickIcon" />
                    <van-goods-action-button color="#FF6203" text="查看类似商品" type="warning" @click="onClickRemove" />
                </van-goods-action>
            </view>
        </view>
        <!-- 规格选择 -->
        <!-- <specsPopup :showSpecsPopup="showSpecsPopup" :buttonStatus="buttonStatus" @closeSpecsPopup="closeSpecsPopup"
            :parentSign="parentSign" :ebProductAttr="specsList" :ebStoreProduct="ebStoreProduct"
            :ebStoreProductAttrValue="specsPriceList" 
            :biaozhi="params.biaozhi" @submitBuy="submitBuy"> </specsPopup> -->
        <serviceSpecsPopup :showSpecsPopup="showSpecsPopup" :buttonStatus="buttonStatus"
            @closeSpecsPopup="closeSpecsPopup" :parentSign="parentSign" :ebProductAttr="specsList"
            :ebStoreProduct="ebStoreProduct" :ebStoreProductAttrValue="specsPriceList" @submitBuy="submitBuy">
        </serviceSpecsPopup>
        <purchaseNotesPopup :showNotesPopup="showNotesPopup" @closeSpecsPopup="closeSpecsPopup"
            :productTimeConfig="productTimeConfig"></purchaseNotesPopup>
        <guaranteesPopup :showGuaranteePopup="showGuaranteePopup" @closeSpecsPopup="closeSpecsPopup"
            :guarantees="guarantees"></guaranteesPopup>
        <van-toast id="van-toast" />
        <!-- 下架商品选择 -->
        <removePopup :showpopup="showRemove" :buttonStatus="buttonStatus" @closeRemovePopup="closeRemovePopup" :ebStoreProduct="ebStoreProduct" :goodsType="'service'"> </removePopup>
        <!-- 优惠券 -->
        <productCouponPopup :couponShow="couponShow" :productId="productId" :couponsData="couponsData" @closePopup="closePopup"
            :pageSign="params.biaozhi" :productType="'services'"></productCouponPopup>
        <!-- 拼团说明弹窗 -->
        <groupBuyPopup :show="showGBpopup" @closePopup="closeGBpopup"></groupBuyPopup>
        <canvas style="position:absolute;left:-9999px" canvas-id="qrcode-canvas" :width="qrSize" :height="qrSize" />
        <canvas style="position:absolute;left:-9999px" canvas-id="shareCanvas" width="375" height="667"
            id="shareCanvas" />

        <van-share-sheet :show="showShare" title="立即分享给好友" :options="options" @select="onSelect" @close="onClose" />
    </view>
</template>

<script>
import { topStyleWhite, topStyleBlack } from '@/utils/topColor'
import loading from '@/mycomponents/loading.vue'

// import specsPopup from '@/mycomponents/specsPopup.vue'
import removePopup from '@/mycomponents/shangcheng/removePopup.vue'
import productCouponPopup from '@/mycomponents/shangcheng/productCouponPopup.vue'
import groupBuyPopup from '@/mycomponents/groupBuyPopup.vue'
import purchaseNotesPopup from '@/mycomponents/serviceModule/purchaseNotesPopup.vue'
import serviceSpecsPopup from '@/mycomponents/serviceSpecsPopup.vue'
import guaranteesPopup from '@/mycomponents/serviceModule/guaranteesPopup.vue'

import Toast from '@/wxcomponents/vant/toast/toast'
import { queryServiceProductByIdApi } from '@/api/service'
import { couponProductListApi} from '@/api/mall'
import {getNewCommentListApi } from '@/api/judge'

import { formatRelativeTime } from '@/utils/time-format-utility';
import { formattedDate, formatDateSE,formatOnlyDate } from '@/utils/timeUtils' // 根据实际路径引入工具函数
// import QRCode from 'qrcode'; // 新增引入
import { SOURCE_TYPE } from '@/utils/constant'
import {authMixin} from '@/utils/isLogin' // 引入authMixin 判断是否登录


export default {
    components: {
        // specsPopup,
        removePopup,
        productCouponPopup,
        groupBuyPopup,
        serviceSpecsPopup,
        purchaseNotesPopup,
        guaranteesPopup,
        loading
    },
    data () {
        return {
            isrefresher: false,
            loadingIsShow: true,
            loadingIsShowPage: true,
            title: '产品详情',
            qrSize: 200, // 新增二维码尺寸数据
            shareQR: '',  // 二维码临时路径
            sharePoster: '', // 新增字段，用于保存生成的海报路径
            scrolling: false, // 顶部区域吸顶效果
            bgOpacity: '',
            scrollMT: '',
            scrollView: '',
            scrollTop: 0,
            old: {
                scrollTop: 0
            },
            listTop: 0,
            detailTop: 0,
            value1: 0,
            value2: 'a',
            currentIndex: 0, // 滚动时页面顶部出现的Tab
            isTruncated: true, // 商品标题显示
            lineClamp: 2,
            couponShow: false, // 优惠券弹窗
            xiajia: false,
            isShouQing: false,
            showRemove: false, // 下架商品弹窗 以及判断是否下架
            isRemove: true, // 判断是否下架
            showSpecsPopup: false, // 规格弹窗
            showNotesPopup: false, // 须知弹窗
            showGuaranteePopup:false, // 保障弹窗
            buttonStatus: 0, // 点击加入购物车 或者 立即购买  传入的按钮内容标志
            currentSwiperItem: 0, // 页面最顶部 商品图片轮播图 当前页面
            tabBarList: [
                {
                    typeId: 0,
                    typeName: '商品'
                },
                {
                    typeId: 1,
                    typeName: '评价'
                },
                {
                    typeId: 2,
                    typeName: '详情'
                }
            ],
            sliderImageList: [
                'https://17lelife-bucket.oss-cn-beijing.aliyuncs.com/WeChat-App-Picture/shangcheng/goods_de.png', 'https://17lelife-bucket.oss-cn-beijing.aliyuncs.com/WeChat-App-Picture/surprise/banner_bg.png', 'https://17lelife-bucket.oss-cn-beijing.aliyuncs.com/WeChat-App-Picture/shangcheng/goods_de.png'
            ],
            tipsList: [ '囤货无忧','元气佳人' ],
            isBtn: '',
            isJoinOrder: '去凑单',
            currentBtn: -1,

            couponsData: [ ],
            // 用户评价
            swiperCurrent: 0,
            tabCurrent: 'tabNum1',
            userJudgeData: [],
            userJudgeHasPicsList:[], // 有图的用户评价列表
            productJudgeList:[], // 服务商品评价列表
            productTimeConfig:{},
            guarantees:[],

            params:{},
            parentSign: 'detail',
            tabHeight: 118,
            navHeight: uni.getStorageSync('navHeight'), // 顶部导航栏的高度
            productId: 71,
            contentImage: ['https://17lelife-bucket.oss-cn-beijing.aliyuncs.com/WeChat-App-Picture/shangcheng/goodsPic.png'], // 商品详情图
            
            ebStoreProduct: {},
            specsList:[],  //规格列表
            specsPriceList:[],   //规格对应的价格
            ebStoreProductAttrRelationDTO:[],  //规格
            selectSuk:'',
            isAnimated: false,
            isAnimatedJudge:false,
            isAnimatedDetail:false,   //点击滑动到当前位置  加动画效果
            startTime: 1640707200000, // 给定的起始时间戳，示例值，可替换
            stopTime: 1797662617000, // 给定的结束时间戳，示例值，可替换
            timeDifference: '', // 存储时间差的字符串表示
            remainingTime: '', // 存储剩余时间的字符串表示
            timer: null, // 定时器引用，用于实时更新剩余时间
            days:null,
            hours:null,
            minutes:null,
            seconds:null,
            joinPeopleNum:0,
            productReplyNum:0,
            showGBpopup:false,  //显示拼团弹窗
            myCartNum:0, //购物列表
            shareProduct:{
                id: 1,
                title: "快来看看这款商品",
                price: "￥199.99",
                image: "https://example.com/shared-product-image.jpg"
            },
            showShare: false,
            options: [
                { name: '微信', icon: 'wechat', openType: 'share' },
                { name: '微博', icon: 'weibo' },
                { name: '复制链接', icon: 'link' },
                { name: '分享海报', icon: 'poster' },
                { name: '二维码', icon: 'qrcode' },
            ],
            debounceStatus: {
                submitting: false,  // 提交状态
                deleting: false,    // 删除状态
                adjusting: false    // 数量调整状态
            },
            debounceTimers: {},
            bizType:2,// 1=商品 2=服务 
            subBizType:2, // 如果bizType=2 这个值才有用 1=服务人员 2= 商品
            sortType:1, // 排序类型 1=综合 2=最新
            queryType:2,// 查询类型1=全部 2=有图 3=追评
            serviceUserId:undefined, // 服务人员id
            serviceReservationId:undefined, // 预约id
            pageSize:10,
            pageNum:1,
            loading:false,
            finished:false,
        }
    },
    onShareAppMessage(){
        return{
            title:this.ebStoreProduct.storeName || '超值好物推荐',
            path:`/pages/surprise/index?id=${this.productId}`,  //&shareUser=${uni.getStorageSync('userId')}
            imageUrl: this.sliderImageList[0] || this.ebStoreProduct.image, // 分享缩略图
            success: function (shareRes) {
                this.logShareAction();
                Toast.success('分享成功');
            },
            fail: function (err) {
                console.log(err);
            }
        }
    },
    computed: {
        // parsedNotDate() {
        //     try {
        //         // 添加空值处理和默认值
            // const jsonStr = this.productTimeConfig.notDateValue || '{"weekDay":[],"festival":[],"date":[]}';
            // return JSON.parse(jsonStr);
        //     } catch (e) {
        //         console.error('日期解析错误:', e);
        //         return { weekDay: [], festival: [], date: [] };
        //     }
        // },
        // formattedDates() {
        //     const weekDayMap = ['日', '一', '二', '三', '四', '五', '六'];
        //     const festivalMap = {
        //         new_year: '元旦',
        //         labor_day: '劳动节',
        //         national_day: '国庆节',
        //         spring_festival: '春节'
        //     };
            
        //     let displayText = [];
            
        //     // 处理周限制
        //     if (this.parsedNotDate.weekDay?.length) {
        //         const days = this.parsedNotDate.weekDay.map(d => `周${weekDayMap[d]}`);
        //         displayText.push(`每周 ${days.join('、')}`);
        //     }
            
        //     // // 处理节日
        //     // if (this.parsedNotDate.festival?.length) {
        //     //     const festivals = this.parsedNotDate.festival.map(f => festivalMap[f] || f);
        //     //     displayText.push(`节日 ${festivals.join('、')}`);
        //     // }
            
        //     // // 处理具体日期
        //     // if (this.parsedNotDate.date?.length) {
        //     //     const uniqueDates = [...new Set(this.parsedNotDate.date)];
        //     //     displayText.push(`具体日期 ${uniqueDates.join('、')}`);
        //     // }
            
        //     return displayText.join('·');
        // }
    },
    onLoad (data) {
        const query = uni.createSelectorQuery().in(this)
        setTimeout(() => {
            query.select('.van-goods-action').boundingClientRect(data => {
                console.log(data, 'data.top--00000')// 这个就是距离顶部的高度
                // this.detailTop = data.top // 赋值，待会要用
            }).exec()
        }, 200)
        // const pages = getCurrentPages();
        // if (pages.length === 1) {
        //     // 提示用户可以通过返回首页按钮回到应用的主要页面
        //     uni.showToast({
        //         title: '您可以点击右上角的首页图标返回首页',
        //         icon: 'none',
        //         duration: 3000
        //     });
        // }
        // 取到路由携带的参数
        if (data && data.params) {
            this.params = JSON.parse(decodeURIComponent(data.params))
            console.log(JSON.parse(decodeURIComponent(data.params)))
            console.log('params', this.params)

            this.productId = this.params.productId
            this.shareProduct={
                id: this.params.id,
                title: "快来看看这款商品",
                price: "￥199.99",
                image: "https://example.com/shared-product-image.jpg"
            }
            
            if (this.params.showSpecsPopup) {
                this.showSpecsPopup = this.params.showSpecsPopup
            }
        }
    },
    async onReady () {
        this.userJudgeData = this.userJudgeData.filter(item => item.pics && item.pics!== null && item.pics.length > 0);
        this.productJudgeList = this.productJudgeList.filter(item => item.mpComments && item.mpComments.imageUrls && item.mpComments.commentImgUrls.length > 0);

        const query = uni.createSelectorQuery().in(this)
        // 需要给评论区域设置一个id标识，在这里是demo
        query.select('#judge_box').boundingClientRect(data => {
            console.log(data, data.top, 'data.top')// 这个就是距离顶部的高度
            this.listTop = data.top // 赋值，待会要用
        }).exec()

        // //需要给商品详情区域设置一个id标识，在这里是demo
        query.select('#goodsDetail').boundingClientRect(data => {
            console.log(data.top, 'data.top--')// 这个就是距离顶部的高度
            this.detailTop = data.top // 赋值，待会要用
        }).exec()
    },
    onShow(){
       this.onRefresherMethod()
    },
    onUnload () {
        if (this.timer) {
            clearTimeout(this.timer)
            this.timer = null
        }
    },
    
    beforeDestroy() {
        clearInterval(this.timer); // 在组件销毁前清除定时器，防止内存泄漏
    },
    methods: {
        onRefresherMethod() {
            if (!this.isrefresher) {
                this.loadingIsShow = true
            }
            const productInfo = this.queryServiceProductByIdMethod()
            const couponList = this.getCouponProductList()

            Promise.all([productInfo, couponList]).then(() => {
                console.log('所有api加载完成')
                this.loadingIsShow = false
                this.loadingIsShowPage = false
                // 关闭加载状态 (转动的圈)，需要一点延时才能关闭
                this.time = setTimeout(e => {
                    this.isrefresher = true
                }, 200)
            })

            // // 拼团
            // this.calculateTimeDifference();
            // this.calculateRemainingTime();
            // this.timer = setInterval(() => {
            //     this.calculateRemainingTime();
            // }, 1000);
        },
        formatTime(timeStr) {
            if (!timeStr) return '';
            const time = timeStr.replace(/-/g, '/');
            console.log(time)
            const timestamp = new Date(time).getTime()
            return formatRelativeTime(timestamp);
        },
        formatDate(timestamp) {
            const date = new Date(timestamp);
            const year = date.getFullYear();
            const month = (date.getMonth() + 1).toString().padStart(2, '0');
            const day = date.getDate().toString().padStart(2, '0');
            const hours = date.getHours().toString().padStart(2, '0');
            const minutes = date.getMinutes().toString().padStart(2, '0');
            const seconds = date.getSeconds().toString().padStart(2, '0');
            return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
        },
        // calculateTimeDifference() {
        //     const start = new Date(this.startTime);
        //     const stop = new Date(this.stopTime);
        //     const diff = stop - start;
        //     const days = Math.floor(diff / (1000 * 60 * 60 * 24));
        //     const hours = Math.floor((diff % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
        //     const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60));
        //     const seconds = Math.floor((diff % (1000 * 60)) / 1000);
        //     this.timeDifference = `${days}天 ${hours}小时 ${minutes}分钟 ${seconds}秒`;
        // },
        // calculateRemainingTime() {
        //     const now = new Date().getTime();
        //     if(now < this.startTime){
        //         this.remainingTime = '未开始';
        //         clearInterval(this.timer);
        //         return;
        //     }
        //     if (now >= this.stopTime) {
        //         this.remainingTime = '已结束';
        //         clearInterval(this.timer);
        //         return;
        //     }
        //     const diff = new Date(this.stopTime) - now;
        //     this.days = Math.floor(diff / (1000 * 60 * 60 * 24));
        //     this.hours = Math.floor((diff % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
        //     this.minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60));
        //     this.seconds = Math.floor((diff % (1000 * 60)) / 1000);
        //     this.remainingTime = `${this.days}天 ${this.hours}小时 ${this.minutes}分钟 ${this.seconds}秒`;
        // },

        // 保障部分  转文字显示
        getGuaranteeText() {
            const guaranteeTypesMap = {
                'PROPERTY_LOSS': '财产损失险',
                'SERVICE_ADD': '服务加价',
                'REFUND': '随时退·过期提',
                'RETURN': '七天无理由退货'
            };
            return this.guarantees
                .filter(item => item.guaranteeValue === "true")
                .slice(0, 3)
                .map(item => `${guaranteeTypesMap[item.guaranteeType]}`);
        },
        handleScroll (e) {
            console.log('顶部滚动距离', e.detail.scrollTop)
            this.old.scrollTop = e.detail.scrollTop

            if (e.detail.scrollTop > 0.2 && !this.scrolling) {
                this.scrolling = true
                const query = uni.createSelectorQuery().in(this)
                query.select('#navBar').boundingClientRect(data => {
                    console.log(data.height, 'navBar--')// 这个就是距离顶部的高度
                    this.tabHeight = data.height + 16 + 12 // 赋值，待会要用  navbar+手写tab的高度
                    this.scrollMT = 'margin-top:' + (data.height + 10) + 'px'
                    console.log(this.scrollMT, 'scrollMT',this.tabHeight, 'tabHeight')
                }).exec()

            } else if (e.detail.scrollTop <= 0.2 && this.scrolling) {
                this.scrolling = false
                this.scrollMT = 'margin-top:90px;'
            }
            this.bgOpacity = `background: rgba(255, 255, 255, ${e.detail.scrollTop / 200})`
            // console.log(this.bgOpacity)
        },

        // 商品图片轮播图事件
        changeSwiper (e) {
            this.currentSwiperItem = e.detail.current // 指示点随着轮播图动
        },
        // 点击轮播图上指示点
        swiperDot (index) {
            // console.log(index,'index currentDot')
            this.currentSwiper = index // 轮播图随着指示点动
        },

        // 返回的箭头
        onClickLeft () {
            uni.navigateBack()
        },

        // 滑动时出现的tab
        changeTab (index, e) {
            this.currentIndex = index
            console.log(e, '090909', this.tabHeight, this.old.scrollTop, 'this.old.scrollTop')

            this.scrollTop = this.old.scrollTop

            if (index === 0) {
                this.$nextTick(function () {
                    this.isAnimated=true
                    this.isAnimatedJudge=false
                    this.isAnimatedDetail=false
                    this.scrollTop = 0
                })
            } else if (index === 1) {
                this.$nextTick(function () {
                    this.isAnimated=false
                    this.isAnimatedJudge=true
                    this.isAnimatedDetail=false
                    // this.scrollTop='579'
                    // 得出的top要减去 固定的tab的高度
                    this.scrollTop = this.listTop - this.tabHeight
                    console.log(this.scrollTop, 'ooo909090uiiu')
                })
            } else {
                this.$nextTick(function () {
                    this.isAnimated=false
                    this.isAnimatedJudge=false
                    this.isAnimatedDetail=true
                    this.scrollTop = this.detailTop - this.tabHeight
                })
            }
        },


        // 控制商品名称的隐藏和显示
        toggleTextDisplay () {
            this.isTruncated = !this.isTruncated
            // if(this.isTruncated){
            //     this.lineClamp='initial'
            // }else{
            //     this.lineClamp=2

            // }
        },

        // 显示弹窗
        onClickCoupons (index) {
            this.couponShow = true
            topStyleWhite()
        },
        // 隐藏弹窗
        closePopup () {
            this.couponShow = false
            topStyleBlack()
        },
        // 须知弹窗
        showNotes(){
            this.showNotesPopup=true
        },

        // 保障弹窗
        showGuarantees(){
            this.showGuaranteePopup=true
        },
        // 显示拼团弹窗
        onClickTiPS(){
            this.showGBpopup=true
        },
        // 隐藏拼团说明弹窗
        closeGBpopup(){
            this.showGBpopup=false
        },
        // 我的购物车
        onClickMyCart () {
            uni.navigateTo({
                url:
                    '/pages/shoppingCart/gouwuche'
            })
        },

        // 生成二维码 
        async generateShareQR() {
            try {
                const ctx = uni.createCanvasContext('qrcode-canvas', this);
                const url = `/pages/shangcheng/goodsDetail?id=${this.productId}`;

                return new Promise((resolve, reject) => {
                    // 使用qrcode-generator库
                    const QRCode = require('qrcode-generator');
                    const qr = QRCode(0, 'H');
                    qr.addData(url);
                    qr.make();

                    // 计算模块尺寸
                    const moduleCount = qr.getModuleCount();
                    const moduleSize = this.qrSize / moduleCount;

                    // 绘制二维码
                    ctx.setFillStyle('#000000');
                    for (let row = 0; row < moduleCount; row++) {
                        for (let col = 0; col < moduleCount; col++) {
                            if (qr.isDark(row, col)) {
                                ctx.fillRect(
                                    col * moduleSize,
                                    row * moduleSize,
                                    moduleSize,
                                    moduleSize
                                );
                            }
                        }
                    }

                    ctx.draw(true, () => {
                        uni.canvasToTempFilePath({
                            canvasId: 'qrcode-canvas',
                            success: res => {
                                this.shareQR = res.tempFilePath;
                                resolve(res.tempFilePath);
                            },
                            fail: err => reject(err)
                        }, this);
                    });
                });
            } catch (error) {
                console.error('二维码生成失败:', error);
                throw error;
            }
        },

        // 生成分享海报
        async createSharePoster() {
            try {
                const [qrCode, goodsImage] = await Promise.all([
                    this.generateShareQR(),
                    this.downloadFile(this.sliderImageList[0])
                ]);

                const ctx = uni.createCanvasContext('shareCanvas', this);

                // 绘制背景（白色底图）
                ctx.fillStyle = '#ffffff';
                ctx.fillRect(0, 0, 375, 667);

                // // 绘制商品主图
                // ctx.drawImage(goodsImage, 0, 0, 375, 500);

                // 绘制商品图
                await new Promise(resolve => {
                    ctx.drawImage(goodsImage, 0, 0, 375, 500);
                    ctx.draw(true, resolve);
                });

                // 绘制商品信息区域
                ctx.fillStyle = '#f5f5f5';
                ctx.fillRect(0, 500, 375, 167);

                // 绘制商品名称（自动换行）
                ctx.setFontSize(16);
                ctx.setFillStyle('#333');
                this.wrapText(ctx, this.ebStoreProduct.storeName, 20, 520, 335);

                // 绘制价格
                ctx.setFontSize(20);
                ctx.setFillStyle('#FF6203');
                ctx.fillText(`¥${this.ebStoreProduct.price}`, 20, 580);

                // 绘制二维码
                // ctx.drawImage(qrCode, 275, 540, 80, 80);
                 // 绘制二维码
                await new Promise(resolve => {
                    ctx.drawImage(qrCode, 275, 540, 80, 80);
                    ctx.draw(true, resolve);
                });

                // ctx.draw();
                // 最终绘制完成
                await new Promise(resolve => ctx.draw(true, resolve));

                // 获取高清临时路径
                const { tempFilePath } = await uni.canvasToTempFilePath({
                    canvasId: 'shareCanvas',
                    quality: 1,  // 最高质量
                    fileType: 'png'
                }, this);

                if (!tempFilePath) throw new Error('生成海报路径失败');
                return tempFilePath;
            } catch (error) {
                console.error('海报生成失败:', error);
                throw error;
            }
        },

        // 文件下载方法
        async downloadFile(url) {
            return new Promise((resolve, reject) => {
                uni.downloadFile({
                    url,
                    success: res => resolve(res.tempFilePath),
                    fail: reject
                });
            });
        },

        // 文字换行辅助方法
        wrapText(ctx, text, x, y, maxWidth) {
            const words = text.split('');
            let line = '';

            for (let n = 0; n < words.length; n++) {
                const testLine = line + words[n];
                const metrics = ctx.measureText(testLine);
                if (metrics.width > maxWidth && n > 0) {
                    ctx.fillText(line, x, y);
                    line = words[n];
                    y += 20; // 行高
                } else {
                    line = testLine;
                }
            }
            ctx.fillText(line, x, y);
        },

        async handleShareAction() {
            try {
                uni.showLoading({ title: '准备分享内容...' });

                // 确保海报生成流程完成
                if (!this.sharePoster) {
                    await this.toShareProduct();
                }

                // 触发原生分享面板
                this.showShare = true;
            } catch (error) {
                console.error('分享流程错误:', error);
                Toast.fail('分享准备失败');
            } finally {
                uni.hideLoading();
            }
        },
        // 分享功能
        async toShareProduct() {
            try {
                uni.showLoading({ title: '生成分享图中...' });
                const poster = await this.createSharePoster();
                this.sharePoster = poster; // 将生成的海报路径保存到 data 中
                uni.hideLoading();
                console.log('海报生成成功:', poster);
                Toast.success('海报已生成，点击分享按钮即可分享');
            } catch (error) {
                uni.hideLoading();
                Toast.fail('分享内容生成失败');
                console.error('分享失败:', error);
            }
        },
        // 真正的分享方法（由按钮直接触发）
        async realShare() {
            try {
                console.log('realShare', this.sharePoster);
                if (!this.sharePoster || typeof this.sharePoster !== 'string') {
                    Toast.fail('请先生成分享海报');
                    this.toShareProduct()
                    return;
                }
                // 增强路径验证
                const validPrefixes = ['wxfile://', 'http://', 'https://', 'tmp://'];
                console.log(this.sharePoster, this.sharePoster.startsWith('http://'))
                if (!validPrefixes.some(prefix => this.sharePoster.startsWith(prefix))) {
                    console.error('无效文件路径:', { path: this.sharePoster, type: typeof this.sharePoster });
                    Toast.fail('分享路径异常，请重新生成');
                    return;
                }

                // 添加文件存在性检查
                const fileExist = await new Promise(resolve => {
                    uni.getFileInfo({
                        filePath: this.sharePoster,
                        success: () => resolve(true),
                        fail: () => resolve(false)
                    });
                });

                if (!fileExist) {
                    throw new Error('file_not_exists');
                }
                console.log(this.sharePoster, 'poster')
                // 执行分享
                await new Promise((resolve, reject) => {
                    uni.showShareMenu({
                        title: `${this.ebStoreProduct.storeName} | ¥${this.ebStoreProduct.price}`,
                        path: `/pages/shangcheng/goodsDetail?id=${this.productId}`,
                        imageUrl: this.sharePoster,
                        success: () => {
                            Toast.success('分享成功');
                            this.logShareAction();
                            resolve();
                        },
                        fail: (err) => {
                            console.error('分享失败详情:', {
                                error: err,
                                path: this.sharePoster,
                                timestamp: Date.now()
                            });
                            reject(err);
                        }
                    });
                });
            } catch (error) {
                console.error('完整分享错误链:', error);
                if (error.message === 'file_not_exists') {
                    Toast.fail('海报文件丢失，请重新生成');
                    this.sharePoster = null;
                } else {
                    Toast.fail('分享失败，请重试');
                }
            }
        },
        toShareProduct1() {
            console.log('Fenxiang');
            uni.share({
                title: this.shareProduct.title || '分享标题',
                path: `/pages/index/index?productId=${this.shareProduct.id}`,
                success: function (shareRes) {
                    // 分享成功后的回调
                    uni.getShareInfo({
                        shareTicket: shareRes.shareTicket,
                        success: function (infoRes) {
                            console.log(infoRes);
                            // 在这里可以处理获取到的分享信息，比如加密数据encryptedData和初始向量iv等
                            // 这些数据可以用于一些后端解密操作或者统计分享来源等用途
                        },
                        fail: function (err) {
                            console.log(err);
                        }
                    });
                },
                fail: function (err) {
                    console.log(err);
                }
            });
        },

        onClick(event) {
            this.showShare = true
        },

        onClose() {
            this.showShare = false
        },

        async onSelect(event) {
            console.log('on select', event);
            Toast(event.detail.name);
            const option = event.detail.name;
            if (option === '分享海报') {
                try {
                    Toast.loading('准备分享内容...');
                    await this.realShare();  // 改为直接调用异步方法
                } catch (error) {
                    console.error('分享流程错误:', error);
                } finally {
                    this.onClose();
                }

            }
            this.onClose();
        },


        // 加入购物车
        addCart () {
            this.showSpecsPopup = true
            this.buttonStatus = 1            
        },
        // 去购买
        onClickBuy () {
            if (!authMixin()) {
                return;  // 阻止后续代码执行
            }
            this.showSpecsPopup = true
            this.buttonStatus = 2
        },

        submitBuy() {
            if (this.debounceStatus.isSubmitting) return
            this.debounceStatus.isSubmitting = true
            this.debounceTimers.submit = setTimeout(() => {
                this.debounceStatus.submitting = false;
            }, 1000);


            
            const params = {
                source: SOURCE_TYPE.DETAIL,  // 关键参数
                // cartIds: this.selectedRowKeys
            }
            uni.navigateTo({
                url:
                    '/pages/shoppingCart/settlement?params=' +
                    encodeURIComponent(JSON.stringify(params))
            })
    

        },
        // 去拼团
        onClickGroupBuy() {
            authMixin()
            this.showSpecsPopup = true
            this.buttonStatus = 2

            // const params = {}
            // uni.navigateTo({
            //     url:
            //         '/pages/shoppingCart/settlement?params=' +
            //         encodeURIComponent(JSON.stringify(params))
            // })
        },
        // 看相似  打开下架
        onClickRemove () {
            Toast('res.msg 己下架商品 相似弹窗')
            this.showRemove = true
        },
        // 打开规格选择弹窗
        onClickSpecs () {
            console.log('打开弹窗    ----规格')
            // debugger
            if (this.showRemove === true || this.showRemove === 1 || this.isRemove == true) {
                Toast('商品已下架不可选规格')
            } else {
                this.showSpecsPopup = true
                this.buttonStatus = 0
            }
        },

        // 关闭规格弹窗
        closeSpecsPopup (result) {
            this.showSpecsPopup = false
            this.showNotesPopup = false
            this.showGuaranteePopup = false
            if(result === 'success'){
            }
        },
        // 关闭下架
        closeRemovePopup () {
            this.showRemove = false
        },

        // 查看评论列表
        toJudgePage () {
            if (this.productReplyNum == 0) {
                Toast('暂无评价')
                return
            }
            const params ={
                source:'serviceDetail',
                id:this.productId,
                bizType:2, // 1=商品 2=服务
            }
            uni.navigateTo({url: '/pages/userJudges/judgePage?params=' + encodeURIComponent(JSON.stringify(params)) })
        },
        // 评价轮播
        lookInfo (index, e, item) {
            console.log(item,'item')
            this.swiperCurrent = index
            // this.tabCurrent = 'tabNum' + index
            console.log(index, item, '组件', this.tabCurrent, 'tabCurrent++', this.swiperCurrent)
            const params = {}
            params.judgeId = item.mpComments.id
            uni.navigateTo({
                url:
                    '/pages/userJudges/judgeDetail?params=' +
                    encodeURIComponent(JSON.stringify(params))
            })
        },
        // 判断是否有图片
        handleImages(pics) {
            // 判断追评中是否有图片的逻辑
            let isPics;
            if (pics !== null && pics !== '' && pics !== undefined) {
                isPics = true;
            } else {
                isPics = false;
            }
            return isPics;
        },

        /**
         * 接口
         *  
        **/ 

        // 服务商品信息
        queryServiceProductByIdMethod () {
            return new Promise((resolve, reject) => {
                const productParams = {
                    id: this.productId
                }
                queryServiceProductByIdApi(productParams).then((res) => {
                    console.log(res)
                    if (res.code === 200) {
                        console.log('res-----', res.data)
                        let img = res.data.ebStoreProduct.image.replace(/"{1,2}/g, '')
                        res.data.ebStoreProduct.image = img
                        this.ebStoreProduct = res.data.ebStoreProduct // 轮播图  名称  价格等
                        console.log(this.ebStoreProduct,'ebStoreProduct')
                        this.isRemove = !res.data.ebStoreProduct?.isShow // 商品是否下架 false：不显示，商品下架；  true: 显示商品、上架
                        this.showRemove = this.isRemove || false // 商品是否下架 false：不显示，商品下架；  true: 显示商品、上架
                        this.tipsList = res.data?.systemLabelResponse || []// 商品标签     
                        const swiperList = res.data.ebStoreProduct.sliderImage // 商品轮播图
                        this.sliderImageList = swiperList.split(',').map(url => url.trim()).filter(url => url);
                        console.log(this.sliderImageList, 'this.sliderImageList')

                        const contenImg = res.data?.ebStoreProduct?.contentImage  //商品详情图
                        if (contenImg ) {
                            this.contentImage = contenImg.split(',').map(url => url.trim()).filter(url => url);
                        }
                        this.productTimeConfig = res.data?.productTimeConfig || {}
                        this.guarantees = res.data?.guarantees || []

                        this.specsList = res.data?.ebProductAttr || [] // 规格属性列表
                        this.specsPriceList = res.data?.ebStoreProductAttrValue || []  //规格组合对应的价格
                        // 优惠券  时间处理
                        // res.data.coupons.forEach(ele => {
                        //     if (ele.useEndTime) {
                        //         ele.useEndTime = formatDateSE(ele.useEndTime)
                        //     }
                        //     if (ele.startEndTime ) {
                        //         ele.useStartTime = formatDateSE(ele.useStartTime)
                        //     }
                        // })
                        // this.couponsData = res.data.coupons || []
                        // this.couponsData.forEach(item => { // 判断优惠券是否已领取
                        //     this.$set(item, 'isChecked', false)
                        // })
                        this.productReplyNum=res.data.productReplyNum  //评论人数

                        this.userJudgeData=res.data.ebStoreProductReply || []
                        // this.userJudgeData.forEach((ele, index) => {
                        //     // 判断评论中是否有图片
                        //     const isImgs = this.handleImages(ele.attachment)
                        //     this.$set(ele, 'isImgs', isImgs)
                        //     if (isImgs) {
                        //         ele.judgeImgs = ele.attachment.split(',')
                        //     }
                        // })
                        // this.userJudgeHasPicsList = this.userJudgeData.filter(
                        //     item => item.judgeImgs && item.judgeImgs.length > 0
                        // );
                        console.log(this.userJudgeData,'this.userJudgeData',this.userJudgeHasPicsList )

                        // this.userJudgeData.filter(item=>{
                        //     console.log(item,'item')
                        //     if(item.attachment!==null &&item.judgeImgs && item.judgeImgs.length>0){
                        //         return item
                        //     }
                        // })
                       
                        if (this.ebStoreProduct.stock === 0) {
                            this.isShouQing = true
                        }
                        // 构建以产品为核心的数据结构
                        let productData = {};
                        res.data.ebStoreProductAttrValue.forEach(attrValue => {
                            let productId = attrValue.productId;
                            if (!productData[productId]) {
                                productData[productId] = {
                                    attributes: [],
                                    attributeValues: [],
                                    relations: []
                                };
                            }
                            productData[productId].attributeValues.push(attrValue);
                        });

                        res.data.ebProductAttr.forEach(attr => {
                            for (let productId in productData) {
                                productData[productId].attributes.push(attr);
                            }
                        });
                        if(this.productReplyNum > 0) {
                            this.getProductCommentList()
                        }
                        resolve(res)
                    } else {
                        reject(res)
                    }
                })
            })
        },
        // // 拼团详情
        // getGroupBuyingProductMethod(){
        //     return new Promise((resolve, reject) => {
        //         const productParams = {
        //             id: this.productId
        //         }
        //         getGroupBuyingProductApi(productParams).then((res) => {
        //             console.log(res)
        //             if (res.code === 200) {
        //                 console.log('res-----', res.data)
        //                 this.ebStoreProduct = res.data[0].ebStoreGroupBuyingProduct // 轮播图  名称  价格等
        //                 const tips = this.ebStoreProduct.label // 商品标签
        //                 this.tipsList=tips.split("，"); // 使用逗号作为分隔符，将字符串分割成数组   商品标签
        //                 // 商品轮播图
        //                 // const swiperList = res.data[0].ebStoreGroupBuyingProduct.images
        //                 // this.sliderImageList = JSON.parse(swiperList)
             
        //                 this.startTime=this.ebStoreProduct.startTime
        //                 this.stopTime=this.ebStoreProduct.stopTime

        //                 const contenImg = this.ebStoreProduct.content_image  //商品详情图
        //                 if (contenImg !== '' && contenImg !== null && contenImg !== undefined) {
        //                     // contenImg=JSON.parse(contenImg)
        //                     this.contentImage.push(contenImg)
        //                 }
        //                 if (this.ebStoreProduct.stock === 0) {
        //                     this.isShouQing = true
        //                 }


        //                 const specsListData=res.data[0].ebProductAttr
        //                 specsListData.forEach(item=>{
        //                     item.ebProductAttrSecond.forEach(i=>{
        //                         this.$set(i, 'specCategoryIndex', '')
        //                     })
        //                     item.curObj={attrName:""}   //没有生效

        //                 }) // 规格 
        //                 this.specsList = specsListData
        //                 this.ebStoreProductAttrRelationDTO=res.data[0].ebStoreProductAttrRelationDTO
        //                 this.specsPriceList=res.data[0].ebStoreProductAttrValue   //规格组合对应的价格
        //                 console.log(this.specsList,this.ebStoreProductAttrRelationDTO,this.specsPriceList,'000pppooo')


                    
        //                 this.joinPeopleNum=res.data[0].joinPeopleNum   //已参团人数
        //                 this.productReplyNum=res.data[0].productReplyNum  //评论人数
        //                 res.data[0].ebStoreProductReply.forEach(ele=>{
        //                     ele.pics= JSON.parse(ele.pics)
        //                     if(ele.createTime!=='' && ele.createTime!==null && ele.createTime!==undefined){
        //                         ele.createTime=formatOnlyDate(ele.createTime)
        //                     }
        //                 }) //评论数据
        //                 // this.userJudgeData=res.data[0].ebStoreProductReply
        //                 // debugger
        //                 const judgeList=res.data[0].ebStoreProductReply
        //                 judgeList.filter(item=>{
        //                    if(item.pics && item.pics!==null && item.pics.length>0){
        //                     return item
        //                    } 
        //                 })
        //                 this.userJudgeData=judgeList
        //                 console.log(this.userJudgeData,'pinglun')
                       


        //                 resolve(res)
        //             } else {
        //                 reject(res)
        //             }
        //         })
        //     })
        // },
        // 记录分享行为（需要对接后端API）
        logShareAction() {
            // 调用后端接口记录分享数据
        },
        // 获取商品评论列表
        getProductCommentList() {
            this.productJudgeList = []
            this.pageNum = 1
            // if (this.loading || this.finished) return;
            // this.loading = true;
            getNewCommentListApi({
                bizType: this.bizType,// 1=商品 2=服务
                subBizType: this.bizType == 1 ? undefined : this.subBizType,// // 如果bizType=2 这个值才有用 1=服务人员 2= 商品
                serviceUserId: this.bizType == 1 ? undefined :this.serviceUserId,  // 服务人员id
                serviceReservationId: this.bizType == 1 ? undefined :this.serviceReservationId, // 服务预约id
                productId: this.subBizType==1 ? undefined : this.productId, // 商品id
                queryType: this.queryType, // 1=全部 2=有图 3=追评 
                sortType: this.sortType, // 1=综合 2=最新
                pageNum: this.pageNum,
                pageSize: this.pageSize,
            }).then(res => {
                console.log(res, '商品评论列表')
                // this.total = res.data.total;
                if (res.code == 200) {
                    this.productJudgeList = (this.pageNum == 1 || !res.data.list)
                        ? (res.data.list || [])
                        : [...this.productJudgeList, ...(res.data.list || [])];
                    // this.finished = this.productJudgeList.length >= this.total;
                    this.productJudgeList.forEach((ele, index) => {
                        ele.mpComments.publishTime = this.formatTime(ele.mpComments.createTime)
                        // const hasImgs = this.handleImages(ele.mpComments.imageUrls)
                        ele.mpComments.commentImgUrls = ele.mpComments.imageUrls?ele.mpComments.imageUrls.split(','):[]
                        // this.$set(ele.mpComments, 'hasImgs', hasImgs)
                        // if(ele.mpComments.hasFollowup==1){
                        //     ele.mpCommentsFollowups.publishTime = this.formatTime(ele.mpCommentsFollowups.followupTime)
                        //     ele.mpCommentsFollowups.formattedPublishTime= this.formatDateAndTime(ele.mpComments.createTime,ele.mpCommentsFollowups.followupTime)
                        //     ele.mpCommentsFollowups.hasFollowUpsImgs = this.handleImages(ele.mpCommentsFollowups.imageUrls)
                        //     ele.mpCommentsFollowups.followupsImageUrls = ele.mpCommentsFollowups.imageUrls?ele.mpCommentsFollowups.imageUrls.split(','):[]
                        // }
                    })
                    this.pageNum++;
                    console.log(this.productJudgeList, 'this.productJudgeList')
                    // resolve(res)
                } else {
                    // reject(res)
                }
            }).finally(() => {
                this.loading = false;
            })
        },
        // 商品对应的优惠券信息
        getCouponProductList() {
            return new Promise((resolve, reject) => {
                couponProductListApi({
                    productId: this.productId,
                }).then((res) => {
                    console.log(res, '优惠券信息')
                    if (res.code == 200) {
                        this.couponsData = res.data
                        this.couponsData.forEach(item => { // 判断优惠券是否已领取
                            this.$set(item, 'isChecked', false)
                        })
                        resolve(res)
                    } else {
                        reject(res)
                    }
                })
            })
        },


    }
}

</script>

<style lang="scss" scoped>
::v-deep .van-nav-bar {
    background-color: transparent !important;
}

.content {
    display: flex;
    flex-direction: column;
    box-sizing: border-box;
    // height: 100vh;
    height: calc(100vh - 63px);
    overflow-y: auto;
    z-index: -2;
    background-size: 100%;
    background-color: #ffffff;

}

.main {
    position: relative;
    // margin-bottom:36px;
    display: flex;
    flex-direction: column;
    box-sizing: border-box;
    height: 100vh;
    background-color: transparent;

    .fixed_top {
        position: fixed;
        width: 100%;
        z-index: 999;
    }

    .top_display {
        display: none;
    }
}

.tabBox {
    position: relative;
    margin-top: 90px;
    // border-bottom: 1px solid #E0E0E0;
}

.content-top {
    .tabs {
        margin-bottom: 12px;
        // 需修改 原来是20px
        padding-left: 10px;
        padding-right: 10px;
        height: 16px;
        line-height: 16px;
        display: flex;
        align-items: center;
        justify-content: space-between;
    }

    .white {

        .tab-item {
            font-size: 28rpx;
            // font-weight: bolder;
            color: #666666;
        }

        .tabbar-item {
            flex: auto;
            z-index: 1;
            text-align: center;

            &.active {
                font-style: normal;
                font-weight: bolder;
                font-size: 32rpx;
                line-height: 32rpx;
                color: #111111;
            }
        }
    }
}

.main-container {
    // position: absolute;
    background: #ffffff;
    height: 100vh;
    display: flex;
    flex-direction: column;
    box-sizing: border-box;
    z-index: -1;

}

// 滚动
.scroll-content {
    flex: 1;
    height: 1px;
}

// 动画效果
.element_to_animate{
    transition: all 0.5s ease;
    animation-duration: 1s; /* 动画时长为1秒 */
    animation-timing-function: ease; /* 动画的时间函数，这里是缓动效果 */
}
.animate_class{
    transform: translateY(-0px);
}
.judge_animate_class{
    // transform: translateY(18px);
}

.goodsImg {
    position: relative;
    width: 100%;
    height: 750rpx;

    .top_swiper {
        display: block;
        height: 750rpx;
    }

    img {
        width: 100%;
        height: 750rpx;
    }
}

.swiper_item_num {
    position: absolute;
    bottom: 30rpx;
    right: 36rpx;
    border-radius: 25px;
    background: rgb(0, 0, 0, 0.5);
    padding-left: 12px;
    padding-right: 12px;
    height: 50rpx;
    line-height: 50rpx;
    font-size: 28rpx;
    text-align: center;
    color: #FFFFFF;
}

.status_tips {
    position: absolute;
    width: 100%;
    height: 108rpx;
    line-height: 108rpx;
    background: rgb(240, 240, 240, 0.6);
    bottom: 0rpx;
    align-items: center;
    font-size: 28rpx;
    text-align: center;
    color: #666666;
}
.group_status_tips{
    position: absolute;
    width: 100%;
    height: 108rpx;
    line-height: 108rpx;
    background:#FF6203;
    bottom: 0px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 28rpx;
    text-align: center;
    color: #666666;

    .status_tips_left{
        padding-left: 48rpx;
        text-align: left;

        .joinPeopleNum{
            font-size: 24rpx;
            color: #ffffff;
            line-height: 24rpx;
        }
        .stopTimeTips{
            margin-top: 8rpx;
            font-size: 24rpx;
            color: #ffffff;
            font-weight: bolder;
            line-height: 24rpx;
        }
    }
    .status_tips_right{
        padding-right: 48rpx;
        font-size:24rpx;
        text{
            display: inline-block;
            width:38rpx;
            height: 38rpx;
            line-height: 38rpx;
            color: #FF6203;
            background-color: #ffffff;
            font-size:24rpx;
            text-align: center;
            border-radius: 2px;
        }
        span{
            color: #ffffff;
            margin-right: 10rpx;
            margin-left: 10rpx;
        }
    }
}

.goods_content {
    background: #ffffff;
    padding: 33px 19px 25px 19px;
}

//商品标题
.goods_detail {
    // position: relative;
    width: 100%;
    /* 定义容器宽度 */
    // overflow: hidden; /* 防止内容溢出 */
    // display: -webkit-box; /* 使用弹性盒子布局模型 */
    // -webkit-box-orient: vertical; /* 垂直排列子元素 */
    // -webkit-line-clamp: 2; /* 限制在两行 */
}

.text {
    // display: -webkit-box; /* 使用弹性盒子布局模型 */
    // // -webkit-box-orient: vertical; /* 垂直排列子元素 */
    // -webkit-line-clamp: 2; /* 限制在两行 */
    // overflow: hidden; /* 隐藏超出容器的内容 */
    // text-overflow: clip;
    color: #111111;
    font-size: 44rpx;
    text-align: left;
    line-height: 30px;
}

.ellipsis {
    -webkit-line-clamp: initial;
    max-height: none;
}

.icon {
    position: absolute;
    right: 0px;
    bottom: 0px;

    img {
        width: 11px;
        height: 6px;
    }
}

.goods_tips {
    display: flex;
    margin-top: 18px;
    justify-content: flex-start;
}

.tips_item {
    height: 28px;
    line-height: 28px;
    font-size: 24rpx;
    text-align: center;
    color: #666666;
    padding-left: 10px;
    padding-right: 10px;
    margin-right: 10px;
    border-radius: 22px;
    background: #f9f9f9;
}

// 价格
.goods_price {
    display: flex;
    align-items: center;
    margin-top: 18px;
    text-align: left;
    line-height: 40rpx;

    .goods_price_num {
        font-weight: bolder;
        font-size: 40rpx;
        text-align: left;
        color: #111111;
        line-height: 40rpx;
    }

    .goods_price_text {
        font-size:24rpx;
        text-align: left;
        color: #111111;
        line-height: 24rpx;
    }
}

// 规格
.goods-specs {
    background: #ffffff;
    margin: 0px 24px;
    padding: 26px 0px 0px 0px;

    border-top: 1px solid #E1E1E1;
    // border-bottom: 1px solid #E1E1E1;


    .goods-specs-item{
        display: flex;
        align-items: center;
        justify-content: space-between;
        font-size: 28rpx;
        line-height: 28rpx;
        text-align: left;
        color: #111111;
    }
    .goods-specs-selected {
        font-size: 28rpx;
        line-height: 28rpx;
        color: #b3b3b3;
        text-align: left;
    }

}

// 优惠券
.coupon {
    background: #ffffff;
    display: flex;
    justify-content: space-between;
    margin: 0px 24px;
    padding: 26px 0px;
    // border-bottom: 1px solid #E1E1E1;
    border-top: 1px solid #E1E1E1;
    align-items: center;

    .coupon-type {
        font-size: 20rpx;
        text-align: center;
        color: #FF6203;
        border-radius: 1px;
        border: 1px solid #FF6203;
        padding-left: 2px;
        padding-right: 2px;
        margin-right: 10px;
    }

    .coupon-type:not(:nth-child(even)):last-child {
        margin-right: 0;
    }

    .left-arrow {
        font-size: 28rpx;
        text-align: left;
        color: #b3b3b3;
        line-height: 28rpx;
    }
}

// 用户评价
.user-judge {
    padding: 0px 0px 20px 24px;
    background: #ffffff;

    .user-judge-title {
        display: flex;
        align-items: center;
        justify-content: space-between;
        // padding-right: 24px;
        border-top: 1px solid #E1E1E1;
        padding-top: 26px;
        margin-right: 24px;
        // padding-bottom: 26px;

        .title {
            font-weight: bolder;
            font-size: 36rpx;
            text-align: left;
            color: #111111;
            line-height: 36rpx;
        }
    }

    .judge_content {
        margin-top: 18px;

        .userJudge_box {
            position: relative;
        }

        .userJudge_content {
            position: relative;
            display: flex;

            .judgeContainer {
                padding: 13px 15px;
                margin-bottom: 15px;
                background: #ffffff;
                box-shadow: 1px 1px 5px 0 rgb(231, 231, 231, 0.29);
                border: 1px solid #f0f0f0;

                // 评价人的信息 时间
                .user_judge_top {
                    display: flex;
                    width: 432rpx;

                    .user_img {
                        line-height: 80rpx;
                        height: 80rpx;
                        width: 80rpx;
                        margin-right: 24rpx;

                        img {
                            width: 80rpx;
                            height: 80rpx;
                            border-radius: 50%;
                        }
                    }

                    .user_info {
                        display: flex;
                        flex-direction: column;
                        justify-content: space-around;
                        line-height: 80rpx;
                        text-align: left;
                        
                        .user_nicheng {
                            font-weight: bolder;
                            font-size: 24rpx;
                            line-height: 24rpx;
                            text-align: left;
                            color: #111111;
                            // margin-left: 14rpx;
                        }

                    }
          
                    .user_judge_date {
                        font-size: 20rpx;
                        // text-align: right;
                        color: #b3b3b3;
                        line-height: 20rpx;
                    }
                }

                // 评价内容的文字
                .judge_comment {
                    color: #111111;
                    font-size: 24rpx;
                    text-align: left;
                    line-height: 24rpx;
                    width: 432rpx;
                    text-overflow: ellipsis;
                    overflow: hidden;
                    white-space: nowrap;
                    margin-top: 29px;
                    margin-bottom: 15px;
                }

                // 评价内容的三张图
                .judge_img {
                    display: flex;
                    height: 112rpx;
                    width: 432rpx;

                    .judge_img_item {
                        width: 25%;
                        margin-right: 18rpx;
                        max-height: 112rpx;
                    }

                    .judge_img_item:last-child {
                        margin-right: 0rpx;
                    }

                    img {
                        width: 100%;
                        height: auto;
                    }
                }

            }
        }
    }

    // 用户评价轮播组件
    .top-menu-view {
        display: flex;
        white-space: nowrap;
        width: 100%;

        .judgeContainer {
            display: inline-block;
            margin-right: 11px;
            position: relative;
        }

        .judgeContainer:last-child {
            margin-right: 5px;
        }
    }

    .fixDiv {
        min-height: 200px;
        width: 10px;
        right: 0px;
        background: linear-gradient(270deg, #ffffff 25.52%, rgba(255, 255, 255, 0) 100%);
        position: absolute;
        z-index: 1;
    }

    .last-top-menu-view {
        width: calc(100% - 10px);
    }
}

// 商品详情图
.goodsPic {
    width: 100%;
    padding-bottom: 72px;
    img {
        width: 100% !important;
        display: block;
        object-fit: contain; // 保持图片原始比例
        margin: 0 auto; // 水平居中
    }
}
// 新增响应式处理
@media screen and (max-width: 750px) {
    .goodsPic img {
        max-width: 100% !important;
    }
}
.goodsAction {

    #goodact {
        position: relative;
    }
    // 售罄商品提示
    .shouqingTips {
        padding-left: 48rpx;
        padding-right: 48rpx;
        position: absolute;
        top: -108rpx;
        left: 0;
        width: calc(100% - 96rpx);
        height: 108rpx;
        line-height: 108rpx;
        background: rgb(240, 240, 240, 0.6);
        text-align: center;
        font-size: 28rpx;
        text-align: center;
        color: #666666;
        display: flex;
        justify-content: space-between;
        align-items: center;
        z-index: 999;

    }


    // 下架商品提示
    .removeTips {
        padding-left: 48rpx;
        padding-right: 48rpx;
        position: absolute;
        top: -108rpx;
        left: 0;
        width: calc(100% - 96rpx);
        height: 108rpx;
        line-height: 108rpx;
        background: rgb(240, 240, 240, 0.6);
        display: flex;
        justify-content: center;
        align-items: center;
        text-align: center;
        font-size: 28rpx;
        color: #666666;
        z-index: 999;
        margin: 0 auto;
    }

}

.goods_act_box {
    position: relative;
    background-color: #ffffff;
    height: 72px;
}

// 在style部分添加
.share-button::after {
  border: none;
  padding: 0;
  margin: 0;
}

.loading {
    text-align: center;
    margin-top: 16px;
    color: #242629;
    font-size: 28rpx;
}


.pl15 {
    padding-left: 15px;
}

.l20 {
    margin-left: 20px;
}
.r12{
    margin-right: 12px;
}
.r13 {
    margin-right: 13px;
}

.r8 {
    margin-right: 8px;
}

::v-deep .van-icon-arrow {
    color: #b3b3b3 !important;
}

::v-deep .van-info {
    background-color: #FF6203;
}
button{
    padding-left: 0rpx !important;
    padding-right: 0rpx !important;
}
::v-deep .van-nav-bar__left {
    width: 56px;
    height: 44px;
}

::v-deep .van-icon {
    color: #242629 !important;
}


::v-deep .van-nav-bar__title {
    font-size: 28rpx;
    color: #333333;
}

::v-deep .van-hairline--bottom:after {
    border: none;
}

::v-deep .van-empty__image {
    width: 150px;
    height: 100px;

}
::v-deep .rich-text img {
    max-width: 100% !important;
    height: auto !important;
    display: block;
    margin: 0 auto;
}

</style>
